<?php


namespace app\admin\controller\coupon;

use app\admin\controller\Controller;
use app\common\service\coupon\CouponSyncService;
use app\model\BaseSupplier;
use app\model\CouponBrand;
use app\model\CouponBrandType;
use app\model\CouponCate;
use app\model\CouponProduct;
use app\Request;
use app\model\CouponProductChannel;
use app\admin\validate\Coupon\ProductChannel as ProductChannelValidate;

class ProductChannel extends Controller
{

    /**
     * 会员卡券商品管理——获取各个下拉框
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function getStatus()
    {
        return success('请求成功', (new CouponProductChannel())->getStatus());
    }

    /**
     * 会员卡券商品管理——获取各个下拉框
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function getBaseSupplierList()
    {
        return success('请求成功', (new BaseSupplier())->getSelectRows());
    }

    /**
     * 会员卡券商品管理——货源对接列表
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function getProductChannel(Request $request)
    {
        $params = $request->param();
        $list = (new CouponProductChannel())->productChannelList($params);
        return success('请求成功',$list);
    }

    /**
     * 会员卡券商品管理——同步商品
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function syncProductChannel()
    {
        $service = new CouponSyncService();
        //同步亿奇达
        $service->sync(CouponSyncService::CHANNEL_YIQIDA);
        //同步鲸充,todo v2.3.7版本暂不对接
        //$service->sync(CouponSyncService::CHANNEL_JINGCHONG);
        return success('同步成功');
    }

    /**
     * 会员卡券商品管理——商品对接(支持多个)
     * @access public
     * @method Patch
     * @return \think\response\Json
     */
    public function productChannelButt(Request $request)
    {
        $ids = make_semiangle($request->param('ids'));
        if (empty($ids)) {
            return fail('货源id不能为空');
        }
        $productChannel = explode(',',$ids);
        $fail = array();
        $isButt = array();
        foreach ( $productChannel as $id) {
            $info = CouponProductChannel::where('status', CouponProductChannel::STATUS_ACTIVE)->where('id', $id)->findOrEmpty();
            if ($info->isEmpty()) {
                $fail[] = $id;
                continue;
            }
            if ($info->butt == CouponProductChannel::BUTT_ACTIVE) {
                $isButt[] = $id;
                continue;
            }
            $info->butt = CouponProductChannel::BUTT_ACTIVE;
            $boolean =$info->save();
            if (!$boolean) {
                $fail[] = $id;
            }
        }
        //全部失败被认为是失败
        if (count($fail) == count($productChannel)) {
            return fail('对接失败');
        }
        $str = '';
        if (!empty($fail)) {
            $str.= '以下商品id对接失败'.implode(',', $fail);
        }
        if (!empty($isButt)) {
            $str.= '以下商品id已经对接过'.implode(',', $isButt);
        }
        if (!empty($str)) {
            return fail('对接成功'. $str);
        }
        return success('商品对接成功', $productChannel);
    }

    /**
     * 会员卡券商品管理——直充商品列表
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function getList(Request $request)
    {
        $params = $request->param();
        $list = (new CouponProductChannel())->getList($params);
        return success('请求成功', $list);
    }


    /**
     * 会员卡券商品管理——直充商品——批量上下架
     * @access public
     * @method Patch
     * @return \think\response\Json
     */
     public function shelf(Request $request, ProductChannelValidate $validate)
     {
         $params = $request->only(['id', 'shelf_state']);
         $result = $validate->scene('shelf')->check($params);
         if(!$result) {
             return fail($validate->getError());
         }
         $idArr = explode(',', $params['id']);
         return (new CouponProductChannel())->shelfState($params['shelf_state'], $idArr);
     }

    /**
     * 会员卡券商品管理——直充商品——批量删除
     * @access public
     * @method Delete
     * @return \think\response\Json
     */
    public function del(Request $request)
    {
        $ids = make_semiangle($request->param('ids'));
        if (empty($ids)) {
            return fail('参数错误');
        }
        $idsArr = explode(',', $ids);
        return (new CouponProductChannel())->btachRecovery($idsArr);
    }
    /**
     * 会员卡券商品管理——直充商品——编辑回显
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function showEditRow(Request $request)
    {
        $id = $request->param('id');
        if (!isset($id) || empty($id)) {
            return fail('id不能为空');
        }
        $info = CouponProductChannel::where('id', $id)
            ->where('status', CouponProductChannel::STATUS_ACTIVE)
            ->where('butt', CouponProductChannel::BUTT_ACTIVE)
            ->field('id, name, product_id, brand_id, rule')
            /*->with(['couponCate' => function($query) {
                $query->where('status', 1);
            }])*/->findOrEmpty();
        if ($info->isEmpty()) {
            return fail('商品已不存在或者已经失效');
        }
        //根据brand_id查询分类
        $cate = [];
        if ($info->brand_id) {
            $brand = CouponBrand::where('id', $info->brand_id)
                ->with(['coupon_cate' => function ($query) {
                }])->field('id, name')->findOrEmpty()
                ->toArray();
            foreach ($brand['coupon_cate'] as $v) {
                $cate[$v['id']] = $v['name'];
            }
        }
        //根据product_id查询type_id
        if ($info->product_id) {
            $type_id = CouponProduct::where('id', $info->product_id)->where('status', CouponProduct::STATUS_ACTIVE)->value('type_id');
        }
        $data['row'] = $info->toArray();
        $data['row']['type_id'] = $type_id??0;
        $data['row']['brand_id'] = $info->brand_id??0;
        $data['row']['cate'] = $cate;
        return success('请求成功', $data);
    }

    /**
     * 会员卡券商品管理——直充商品——下拉框联动--分类->品牌
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function selectlinkageCate()
    {
        $list = CouponCate::where('status', CouponCate::STATUS_ACTIVE)->column('name', 'id');
        return success('请求成功', $list);
    }

    /**
     * 会员卡券商品管理——直充商品——下拉框联动--分类->品牌
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function selectlinkageCateBrand(Request $request)
    {
        $cate_id = $request->param('cate_id');
        if (empty($cate_id)) {
            $list = CouponBrand::query()->where('status', CouponBrand::STATUS_ACTIVE)->column('name', 'id');
            return success('请求成功', $list);
            //return fail('请先选择商品分类');
        }
        $list = (new CouponCate())->selectlinkageCateBrand($cate_id);
        return success('请求成功', $list);
    }

    /**
     * 会员卡券商品管理——直充商品——下拉框联动--品牌->充值类型
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function selectlinkageBrandType(Request $request)
    {
        $brand_id = $request->param('brand_id');
        if (empty($brand_id)) {
            return fail('请先选择品牌分类');
        }
        $list = (new CouponBrand())->selectlinkageBrandType($brand_id);
        return success('请求成功', $list);
    }

    /**
     * 会员卡券商品管理——直充商品——下拉框联动--充值类型->面额
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function selectlinkageTypeProduct(Request $request)
    {
        $type_id = $request->param('type_id');
        if (empty($type_id)) {
            return fail('请先选择充值类型');
        }
        $list = (new CouponBrandType())->selectlinkageTypeProduct($type_id);
        return success('请求成功', $list);
    }

    /**
     * 会员卡券商品管理——直充商品——编辑
     * @access public
     * @method Patch
     * @return \think\response\Json
     */
    public function edit(Request $request, ProductChannelValidate $validate)
    {
        $params = $request->only(['id', 'cate_id', 'brand_id', 'type_id', 'product_id', 'rule']);
        $result = $validate->scene('edit')->check($params);
        if(!$result) {
            return fail($validate->getError());
        }
        return (new CouponProductChannel())->doEdit($params);

    }

    /**
     * 会员卡券商品管理——直充商品——批量匹配
     * @access public
     * @method Patch
     */
    public function batchMatch(Request $request)
    {
        //商品id,支持批量,传数组
        $channel_ids = $request->param('ids');
        if (empty($channel_ids)) {
            return fail('参数错误');
        }
        //判读是否存在
        $channels = CouponProductChannel::whereIn('id', $channel_ids)
            ->whereIn('relate_state',[CouponProductChannel::RELETE_STATE_WPP,CouponProductChannel::RELETE_STATE_PPSB])
            ->select();
        if ($channels->isEmpty()) {
            return fail('直充商品不存在或已经被删除或者已经匹配');
        }
        $query = collect($channels);
        $success = array();
        $query->each(function (CouponProductChannel $productChannel) use (&$success){
            //dd($productChannel);
            //查找是否有已经匹配过的产品
            $map = array();
            $map[] = ['name', '=', $productChannel->name];
            $map[] = ['id', '<>', $productChannel->id];
            $map[] = ['product_id', '>', 0];
            $info = (new CouponProductChannel())->queryDataByCondition($map);
            if ($info) {
                $productChannel->product_id = $info->product_id;
                $productChannel->relate_state = CouponProductChannel::RELETE_STATE_YPP;
                if ($productChannel->save()) {
                    $success[] = $productChannel->id;
                }
            } else {
                //保存匹配失败
                $productChannel->relate_state = CouponProductChannel::RELETE_STATE_PPSB;
                $productChannel->save();
            }
        });
        if (empty($success)) {
            return fail('匹配失败或者选择的数据之前已经匹配成功');
        }
        return success('匹配成功的商品id:['.implode(',',$success));
    }
}